package common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

public class ObjectFileStoring<T extends Serializable> implements Storing<T> {
	private String pathname;
	private String filename;

	private static final String EXTENSION = ".obf";

	public ObjectFileStoring(String pathname, String filename) {
		this.pathname = pathname;
		this.filename = filename;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> load() throws IOException {
		FileInputStream fis = new FileInputStream(pathname + File.separator + filename + EXTENSION);
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		List<T> object;
		try {
			object = (List<T>) ois.readObject();
		} catch (ClassNotFoundException e) {
			throw new IOException("Formato del file non valido!");
		} finally {
			ois.close();
		}
		return object;
	}

	@Override
	public synchronized void save(List<T> content) throws IOException {
		FileOutputStream fos = new FileOutputStream(pathname + File.separator + filename + EXTENSION);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		oos.writeObject(content);
		oos.close();
	}
}
